Understanding :focus vs :focus-visible in CSS
The :focus pseudo-class applies styles whenever an element receives focus, regardless of how the focus was triggered (keyboard, mouse, or script). In contrast, :focus-visible applies styles only when the browser determines that focus should be visibly indicated, typically for keyboard navigation.
:focus – Styles any element that has focus, triggered by any method.
:focus-visible – Styles elements only when focus should be visibly indicated (usually keyboard or accessibility-related interactions).
Using :focus-visible prevents unnecessary focus styles when clicking with a mouse, improving UX.
:focus-visible respects user preferences and accessibility guidelines.
In this example, when you click the button with a mouse, only the :focus style may apply depending on browser defaults. When you navigate to the button using the keyboard (Tab key), the :focus-visible outline appears, providing a clear visual indicator for keyboard users without distracting mouse users.
Use :focus-visible to provide focus indicators for keyboard and accessibility users without affecting mouse interactions.
Combine :focus and :focus-visible for consistent and accessible focus styling.
Test on multiple browsers, as :focus-visible support varies and may require a polyfill in older browsers.
Maintain sufficient contrast and visible indicators to meet accessibility standards.